package com.saver.modules.sys.service;

import com.saver.common.db.JdbcTool;
import com.saver.common.utils.PageUtils;
import com.saver.common.utils.Query;
import com.saver.common.utils.R;
import com.saver.modules.sys.dao.SysAppendixDao;
import com.saver.modules.sys.dao.SysDownloadDao;
import com.saver.modules.sys.entity.SysAppendixEntity;
import com.saver.modules.sys.entity.SysDownloadEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 文件
 *
 * @author yuxiaolong
 * @email 1005471232@qq.com
 * @date 2018年08月30日 下午10:45
 */
@Service
public class SysDownloadService {

    @Autowired
    private SysAppendixService sysAppendixService;

    @Autowired
    private SysAppendixDao sysAppendixDao;

    @Autowired
    private SysDownloadDao sysDownloadDao;

    @Autowired
    private JdbcTool jdbcTool;

    public PageUtils queryPage(Map<String, Object> params) {
        Query<SysDownloadEntity> query = new Query<>(params);
        String sql = "SELECT sd.uuid,sd.create_date createDate,sd.mark mark,sd.title title,su.username username from sys_download sd LEFT JOIN sys_user su ON sd.user_id = su.user_id";
        String q = (String) params.get("q");
        if (q != null && !q.equals("")) {
            sql = sql + " where sd.title like '%" + q + "%'";
        }
        PageUtils pageUtils = jdbcTool.queryPage(sql, query);
        return pageUtils;
    }

    @Transactional
    public void save(SysDownloadEntity entity, Long userId) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        entity.setUuid(uuid);
        entity.setCreateDate(new Date());
        entity.setUserId(userId);
        this.update(entity);
    }

    @Transactional
    public void update(SysDownloadEntity entity) {
        List<SysAppendixEntity> appendixs = entity.getAppendixs();
        appendixs.forEach(item -> sysAppendixService.update(item.getId(), entity.getUuid()));
        sysDownloadDao.save(entity);
    }

    public SysDownloadEntity get(String uuid) {
        Optional<SysDownloadEntity> byId = sysDownloadDao.findById(uuid);
        if (byId.isPresent()) {
            SysDownloadEntity sysDownloadEntity = byId.get();
            List<SysAppendixEntity> list = sysAppendixDao.findByFileUuid(sysDownloadEntity.getUuid());
            sysDownloadEntity.setAppendixs(list);
            return sysDownloadEntity;
        }
        return null;
    }

    public R delete(String uuid) {
        SysDownloadEntity sysDownloadEntity = this.get(uuid);
        List<SysAppendixEntity> list = sysDownloadEntity.getAppendixs();
        list.forEach(item -> {
            sysAppendixService.deleteAppendix(item.getId());
        });
        sysDownloadDao.deleteById(uuid);
        return R.ok();
    }

}
